package com.hdhere.application.service;

import com.hdhere.application.Repository.media.VideoRepository;
import com.hdhere.domain.common.Pagination;
import com.hdhere.domain.media.QVideo;
import com.hdhere.domain.media.Video;
import com.hdhere.domain.media.page.VideoPagination;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.Expressions;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

@Service
public class VideoService extends BaseService{

    @Autowired
    private VideoRepository videoRepository;

    public Pagination getPage(VideoPagination page){
        var video = QVideo.video;
        Predicate pre = Expressions.asBoolean(true).isTrue();

        if(page.getCatePath() != null)
            pre = ExpressionUtils.and(pre, video.catePath.contains(page.getCatePath()));

        if(StringUtils.isNotBlank(page.getName()))
            pre = ExpressionUtils.and(pre, video.name.like("%"+page.getName()+"%"));

        if(page.getPostState() != null)
            pre = ExpressionUtils.and(pre, video.postState.eq(page.getPostState()));

        Page<Video> date = videoRepository.findAll(pre, page);
        page.setPage(date);
        return page;
    }

    public Video getById(byte[] id){
        return videoRepository.findById(id).orElse(null);
    }

    public void save(Video video){
        video.resetData();
        videoRepository.save(video);
    }
}
